/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package views;

import entities.ControlRopaBlancaEntregada;
import entities.Logs;
import entities.RopaBlanca;
import entities.Usuarios;
import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.Beans;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.Query;
import javax.persistence.RollbackException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import logica.ExcelJTableExporter;

/**
 *
 * @author root
 */
public class ControlRopaBlancaEntregadaView extends JPanel {

    private ControlRopaBlancaEntregada c;
    private Logs logs;
    public static JFrame frame;
    private Usuarios usuario;

    public ControlRopaBlancaEntregadaView(Usuarios user) {
        initComponents();
        if (!Beans.isDesignTime()) {
            entityManager.getTransaction().begin();
        }
        this.usuario = user;
        limpiarBotones();
    }

    private Integer getIDControlRopaBlancaEntregada(RopaBlanca ropaBlanca, int cantidadEntregada, Date fechaEntrega, String encargadoMovimiento, String proveedor) {
        Query queryIDControlRopaBlancaEntregada;
        ControlRopaBlancaEntregada control;
        queryIDControlRopaBlancaEntregada = entityManager.createNamedQuery("ControlRopaBlancaEntregada.findByAll");
        queryIDControlRopaBlancaEntregada.setParameter("ropaBlanca", ropaBlanca);
        queryIDControlRopaBlancaEntregada.setParameter("cantidadEntregada", cantidadEntregada);
        queryIDControlRopaBlancaEntregada.setParameter("fechaEntrega", fechaEntrega);
        queryIDControlRopaBlancaEntregada.setParameter("encargadoMovimiento", encargadoMovimiento);
        queryIDControlRopaBlancaEntregada.setParameter("proveedor", proveedor);
        control = (ControlRopaBlancaEntregada) queryIDControlRopaBlancaEntregada.getSingleResult();
        return control.getIdControlRopaBlancaEntregada();
    }

    public JFrame getFrame() {
        return frame;
    }

    public void setFrame(JFrame frame) {
        ControlRopaBlancaEntregadaView.frame = frame;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("SIAATPU").createEntityManager();
        query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT c FROM ControlRopaBlancaEntregada c");
        list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        ropaBlancaQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT r FROM RopaBlanca r");
        ropaBlancaList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : ropaBlancaQuery.getResultList();
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        ropaBlancaLabel = new javax.swing.JLabel();
        cantidadEntregadaLabel = new javax.swing.JLabel();
        fechaEntregaLabel = new javax.swing.JLabel();
        encargadoMovimientoLabel = new javax.swing.JLabel();
        proveedorLabel = new javax.swing.JLabel();
        fechaEntregaField = new javax.swing.JTextField();
        encargadoMovimientoField = new javax.swing.JTextField();
        proveedorField = new javax.swing.JTextField();
        guardarButton = new javax.swing.JButton();
        cancelarButton = new javax.swing.JButton();
        nuevoButton = new javax.swing.JButton();
        borrarButton = new javax.swing.JButton();
        ropaBlancaComboBox = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();
        ayudaLabel = new javax.swing.JLabel();
        cantidadEntregadaSpinner = new javax.swing.JSpinner();

        FormListener formListener = new FormListener();

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${ropaBlanca}"));
        columnBinding.setColumnName("Ropa Blanca");
        columnBinding.setColumnClass(entities.RopaBlanca.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${cantidadEntregada}"));
        columnBinding.setColumnName("Cantidad Entregada");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${fechaEntrega}"));
        columnBinding.setColumnName("Fecha Entrega");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${encargadoMovimiento}"));
        columnBinding.setColumnName("Encargado Movimiento");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${proveedor}"));
        columnBinding.setColumnName("Proveedor");
        columnBinding.setColumnClass(String.class);
        bindingGroup.addBinding(jTableBinding);

        masterTable.addMouseListener(formListener);
        masterScrollPane.setViewportView(masterTable);

        ropaBlancaLabel.setText("Ropa Blanca:");

        cantidadEntregadaLabel.setText("Cantidad Entregada:");

        fechaEntregaLabel.setText("Fecha Entrega:");

        encargadoMovimientoLabel.setText("Encargado Movimiento:");

        proveedorLabel.setText("Proveedor:");

        fechaEntregaField.setEditable(false);

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), fechaEntregaField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        encargadoMovimientoField.setEditable(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.encargadoMovimiento}"), encargadoMovimientoField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceUnreadableValue(null);
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), encargadoMovimientoField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.proveedor}"), proveedorField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceUnreadableValue(null);
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), proveedorField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        guardarButton.setBackground(new java.awt.Color(1, 154, 210));
        guardarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        guardarButton.setForeground(new java.awt.Color(255, 255, 255));
        guardarButton.setText("Guardar");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), guardarButton, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        guardarButton.addActionListener(formListener);

        cancelarButton.setBackground(new java.awt.Color(1, 154, 210));
        cancelarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        cancelarButton.setForeground(new java.awt.Color(255, 255, 255));
        cancelarButton.setText("Cancelar");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), cancelarButton, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        cancelarButton.addActionListener(formListener);

        nuevoButton.setBackground(new java.awt.Color(1, 154, 210));
        nuevoButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        nuevoButton.setForeground(new java.awt.Color(255, 255, 255));
        nuevoButton.setText("Nuevo");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement == null}"), nuevoButton, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        nuevoButton.addActionListener(formListener);

        borrarButton.setBackground(new java.awt.Color(1, 154, 210));
        borrarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        borrarButton.setForeground(new java.awt.Color(255, 255, 255));
        borrarButton.setText("Borrar");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), borrarButton, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        borrarButton.addActionListener(formListener);

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, ropaBlancaList, ropaBlancaComboBox);
        bindingGroup.addBinding(jComboBoxBinding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.ropaBlanca}"), ropaBlancaComboBox, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), ropaBlancaComboBox, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/xls.png"))); // NOI18N
        jButton1.setText("Exportar");
        jButton1.addActionListener(formListener);

        ayudaLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/help.png"))); // NOI18N
        ayudaLabel.addMouseListener(formListener);

        cantidadEntregadaSpinner.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), Integer.valueOf(0), null, Integer.valueOf(1)));
        cantidadEntregadaSpinner.setEnabled(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.cantidadEntregada}"), cantidadEntregadaSpinner, org.jdesktop.beansbinding.BeanProperty.create("value"));
        bindingGroup.addBinding(binding);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(masterScrollPane, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(ayudaLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(nuevoButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(borrarButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cancelarButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(guardarButton))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(0, 0, Short.MAX_VALUE)
                                        .addComponent(ropaBlancaLabel)
                                        .addGap(59, 59, 59))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(proveedorLabel)
                                            .addComponent(encargadoMovimientoLabel)
                                            .addComponent(fechaEntregaLabel)
                                            .addComponent(cantidadEntregadaLabel))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(encargadoMovimientoField, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(fechaEntregaField, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(ropaBlancaComboBox, javax.swing.GroupLayout.Alignment.TRAILING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(proveedorField, javax.swing.GroupLayout.PREFERRED_SIZE, 383, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(cantidadEntregadaSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(20, 20, 20)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {borrarButton, cancelarButton, guardarButton, nuevoButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(ayudaLabel))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(masterScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(ropaBlancaComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(ropaBlancaLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cantidadEntregadaLabel)
                            .addComponent(cantidadEntregadaSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(fechaEntregaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(fechaEntregaLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(encargadoMovimientoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(encargadoMovimientoLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(proveedorField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(proveedorLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(guardarButton)
                            .addComponent(cancelarButton)
                            .addComponent(borrarButton)
                            .addComponent(nuevoButton)
                            .addComponent(jButton1))
                        .addGap(1, 1, 1)))
                .addContainerGap())
        );

        bindingGroup.bind();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener, java.awt.event.MouseListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == guardarButton) {
                ControlRopaBlancaEntregadaView.this.guardarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == cancelarButton) {
                ControlRopaBlancaEntregadaView.this.cancelarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == nuevoButton) {
                ControlRopaBlancaEntregadaView.this.nuevoButtonActionPerformed(evt);
            }
            else if (evt.getSource() == borrarButton) {
                ControlRopaBlancaEntregadaView.this.borrarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == jButton1) {
                ControlRopaBlancaEntregadaView.this.jButton1ActionPerformed(evt);
            }
        }

        public void mouseClicked(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == masterTable) {
                ControlRopaBlancaEntregadaView.this.masterTableMouseClicked(evt);
            }
        }

        public void mouseEntered(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == ayudaLabel) {
                ControlRopaBlancaEntregadaView.this.ayudaLabelMouseEntered(evt);
            }
        }

        public void mouseExited(java.awt.event.MouseEvent evt) {
        }

        public void mousePressed(java.awt.event.MouseEvent evt) {
        }

        public void mouseReleased(java.awt.event.MouseEvent evt) {
        }
    }// </editor-fold>//GEN-END:initComponents

    private void habilitarBotones(boolean estado) {
        nuevoButton.setEnabled(!estado);
        masterTable.setEnabled(!estado);
        cancelarButton.setEnabled(estado);
        guardarButton.setEnabled(estado);
        borrarButton.setEnabled(estado);
        ropaBlancaComboBox.setEnabled(estado);
        cantidadEntregadaSpinner.setEnabled(estado);
        fechaEntregaField.setEnabled(estado);
        encargadoMovimientoField.setEnabled(estado);
        proveedorField.setEnabled(estado);
    }

    private void limpiarBotones() {
        ropaBlancaComboBox.setSelectedIndex(-1);
        cantidadEntregadaSpinner.setValue(0);
        fechaEntregaField.setText("");
        encargadoMovimientoField.setText("");
        proveedorField.setText("");
    }

    private String formatearFecha(Date fecha) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        String fechaFormateada = sdf.format(fecha);
        return fechaFormateada;
    }

    @SuppressWarnings("unchecked")
    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        entityManager.getTransaction().rollback();
        entityManager.getTransaction().begin();
        java.util.Collection data = query.getResultList();
        for (Object entity : data) {
            entityManager.refresh(entity);
        }
        list.clear();
        list.addAll(data);
        limpiarBotones();
        cantidadEntregadaSpinner.setEnabled(false);
    }//GEN-LAST:event_cancelarButtonActionPerformed

    private void borrarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_borrarButtonActionPerformed
        int[] selected = masterTable.getSelectedRows();
        List<entities.ControlRopaBlancaEntregada> toRemove = new ArrayList<entities.ControlRopaBlancaEntregada>(selected.length);
        for (int idx = 0; idx < selected.length; idx++) {
            entities.ControlRopaBlancaEntregada c = list.get(masterTable.convertRowIndexToModel(selected[idx]));
            toRemove.add(c);
            logs = new Logs();
            logs.setUsuario(usuario);
            logs.setearObservaciones("Borrado", "ControlRopaBlancaEntregada", c.getIdControlRopaBlancaEntregada(), "ControlRopaBlancaEntregadaView");
            entityManager.persist(logs);
            entityManager.remove(c);
        }
        list.removeAll(toRemove);
        entityManager.getTransaction().commit();
        entityManager.getTransaction().begin();
        //guardarButtonActionPerformed(null);
        cancelarButtonActionPerformed(null);
    }//GEN-LAST:event_borrarButtonActionPerformed

    private void nuevoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevoButtonActionPerformed
        c = new entities.ControlRopaBlancaEntregada();
        c.setFechaEntrega(new Date());
        logs = new Logs();
        logs.setUsuario(usuario);
        entityManager.persist(c);
        list.add(c);
        int row = list.size() - 1;
        masterTable.setRowSelectionInterval(row, row);
        masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));
        fechaEntregaField.setText(formatearFecha(c.getFechaEntrega()));
        cantidadEntregadaSpinner.setValue(0);
        encargadoMovimientoField.setText(this.usuario.getNombre());
        borrarButton.setEnabled(false);
        cantidadEntregadaSpinner.setEnabled(true);
    }//GEN-LAST:event_nuevoButtonActionPerformed

    private void guardarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarButtonActionPerformed
        if ("".equals(proveedorField.getText()) || ropaBlancaComboBox.getSelectedIndex() < 0 || ((int) cantidadEntregadaSpinner.getValue() <= 0)) {
            String guardarmensaje = "";
            if ("".equals(proveedorField.getText())) {
                guardarmensaje = guardarmensaje + "                     Proveedor\n";
            }
            if (ropaBlancaComboBox.getSelectedIndex() < 0) {
                guardarmensaje = guardarmensaje + "                     Ropa Blanca:\n";
            }
            if ((int) cantidadEntregadaSpinner.getValue() <= 0) {
                guardarmensaje = guardarmensaje + "                     Cantidad Entregada:\n";
            }

            JOptionPane.showMessageDialog(this, "Revise el/los siguientes campos:\n" + guardarmensaje, "Atención", JOptionPane.INFORMATION_MESSAGE, null);
        } else {
            try {
                logs = new Logs();
                logs.setUsuario(usuario);
                if (c.getIdControlRopaBlancaEntregada() == null) {
                    entityManager.getTransaction().commit();
                    entityManager.getTransaction().begin();
                    Integer idControlRopaBlancaEntregada = getIDControlRopaBlancaEntregada(c.getRopaBlanca(), c.getCantidadEntregada(), c.getFechaEntrega(), c.getEncargadoMovimiento(), c.getProveedor());
                    logs.setearObservaciones("Alta", "ControlRopaBlancaEntregada", idControlRopaBlancaEntregada, "ControlRopaBlancaEntregadaView");
                } else {
                    logs.setearObservaciones("Modificación", "ControlRopaBlancaEntregada", c.getIdControlRopaBlancaEntregada(), "ControlRopaBlancaEntregadaView");
                }
                entityManager.persist(logs);
                entityManager.getTransaction().commit();
                entityManager.getTransaction().begin();
                cancelarButtonActionPerformed(null);
            } catch (RollbackException rex) {
                rex.printStackTrace();
                entityManager.getTransaction().begin();
                List<entities.ControlRopaBlancaEntregada> merged = new ArrayList<entities.ControlRopaBlancaEntregada>(list.size());
                for (entities.ControlRopaBlancaEntregada c : list) {
                    merged.add(entityManager.merge(c));
                }
                list.clear();
                list.addAll(merged);
            }
        }
    }//GEN-LAST:event_guardarButtonActionPerformed

    private void masterTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMouseClicked
        //Le asigno al Text Field de fechaEntrega la fecha correspondiente al elemento seleccionado en la masterTable
        Date fechaControlSeleccionado = ((ControlRopaBlancaEntregada) list.get(masterTable.getSelectedRow())).getFechaEntrega();
        c = list.get(masterTable.getSelectedRow());
        fechaEntregaField.setText(formatearFecha(fechaControlSeleccionado));
        encargadoMovimientoField.setText(this.usuario.getNombre());
        cantidadEntregadaSpinner.setEnabled(true);
    }//GEN-LAST:event_masterTableMouseClicked

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        new ExcelJTableExporter(masterTable, "ControlRopaBlancaEntregada").export();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void ayudaLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ayudaLabelMouseEntered
        ayudaLabel.setToolTipText("En esta pantalla usted puede realizar el control de la ropa blanca entregada");
    }//GEN-LAST:event_ayudaLabelMouseEntered
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel ayudaLabel;
    private javax.swing.JButton borrarButton;
    private javax.swing.JButton cancelarButton;
    private javax.swing.JLabel cantidadEntregadaLabel;
    private javax.swing.JSpinner cantidadEntregadaSpinner;
    private javax.swing.JTextField encargadoMovimientoField;
    private javax.swing.JLabel encargadoMovimientoLabel;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JTextField fechaEntregaField;
    private javax.swing.JLabel fechaEntregaLabel;
    private javax.swing.JButton guardarButton;
    private javax.swing.JButton jButton1;
    private java.util.List<entities.ControlRopaBlancaEntregada> list;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JButton nuevoButton;
    private javax.swing.JTextField proveedorField;
    private javax.swing.JLabel proveedorLabel;
    private javax.persistence.Query query;
    private javax.swing.JComboBox ropaBlancaComboBox;
    private javax.swing.JLabel ropaBlancaLabel;
    private java.util.List<entities.RopaBlanca> ropaBlancaList;
    private javax.persistence.Query ropaBlancaQuery;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    public static void main(Usuarios user) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ControlRopaBlancaEntregadaView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ControlRopaBlancaEntregadaView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ControlRopaBlancaEntregadaView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ControlRopaBlancaEntregadaView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        final Usuarios usuario = user;
        ControlRopaBlancaEntregadaView.frame = new JFrame();
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                frame.setContentPane(new ControlRopaBlancaEntregadaView(usuario));
                frame.pack();
                frame.setVisible(true);
                frame.setTitle("Control de Ropa Blanca Entregada -   Sistema Integrado de Administración de Alquileres Turísticos  ");
                frame.setIconImage(new ImageIcon(getClass().getResource("/images/logo.png")).getImage());
                frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                frame.addWindowListener(new WindowAdapter() {

                    public void windowClosing(WindowEvent e) {
                        if (frame != null) {
                            frame.setVisible(false);
                        }
                        frame = null;
                    }
                });
            }
        });
    }
}
